package com.estate.framework.web.service.data;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.estate.common.core.domain.model.ApiResponse;
import com.estate.common.core.domain.model.enquiry.EnquiryResp;
import com.estate.common.utils.DateUtils;
import com.estate.common.utils.SnowflakeIdWorker;
import com.estate.framework.web.pojo.ListingFilter;
import com.estate.system.domain.Enquiry;
import com.estate.system.service.impl.DataEnquiriesServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Component
public class ZenuEnquiriesApi {

    private static final Logger log = LoggerFactory.getLogger(ZenuEnquiriesApi.class);

    @Resource
    private DataEnquiriesServiceImpl dataEnquiriesServiceImpl;

    @Resource
    public ZenuApiClient client;

    /**
     * 批量保存询盘数据（增量同步，基于时间范围）
     */
    public void saveBatchEnquiries() {
//        log.info("开始保咨询数据");
        Integer count = countNewEnquiries();
        // 同步数据记录
        client.syncDataRecord(count, "Enquiry Data", "success", "Enquiry", null);
        int pages = 0;
        if (count > 0) {
            pages = count % 10 == 0 ? count / 10 : count / 10 + 1;
            if (pages > 100) {
                pages = 100;
            }
        }
        for (int i = 0; i < pages; i++) {
            Map<String, String> filters = getListingFilter();
            List<Enquiry> clients = pageEnquiriesInfo(filters, i + 1, 10);
            dataEnquiriesServiceImpl.saveBatch(clients);
        }
//        log.info("保存咨询数据结束");
    }

    @NotNull
    private static Map<String, String> getListingFilter() {
        // 获取悉尼时区
        ZoneId sydneyZone = ZoneId.of("Australia/Sydney");

        // 获取悉尼当前日期和昨天的日期
        LocalDate sydneyToday = LocalDate.now(sydneyZone);
        LocalDate sydneyYesterday = sydneyToday.minusDays(1);

        // 设置开始时间为悉尼昨天00:00:00
        String startTime = sydneyYesterday.atStartOfDay(sydneyZone).format(DateTimeFormatter.ISO_DATE_TIME);

        // 设置结束时间为悉尼今天23:59:59
        String endTime = sydneyToday.atTime(23, 59, 59).atZone(sydneyZone).format(DateTimeFormatter.ISO_DATE_TIME);

        ListingFilter filters = new ListingFilter();
        filters.setUpdatedDateFrom(startTime);
        filters.setUpdatedDateTo(endTime);
        Map<String, String> filtersMap = new HashMap<>();

        //将filter转为Map<String, String>
        filtersMap.putAll(filters.toMap());

        return filtersMap;
    }

    private Integer countNewEnquiries() {
        try {
            Map<String, String> filters = getListingFilter();
            ApiResponse<List<EnquiryResp>> response = client.getEnquiries(1, 1, filters);
            Long totalRecords = response.getPagination().getTotalRecords();
            return totalRecords.intValue();
        } catch (IOException e) {
            log.error("API调用失败: " + e.getMessage());
            // 同步数据记录
            client.syncDataRecord(0, "Enquiry Data", "failed", "Enquiry", e.getMessage());
        }
        return 0;
    }


    /**
     * 带过滤条件的询盘列表
     *
     * @param filters    过滤条件
     * @param pageNumber 页码
     * @param pageSize   每页大小
     * @return 询盘列表
     */
    public List<Enquiry> pageEnquiriesInfo(Map<String, String> filters, Integer pageNumber, Integer pageSize) {
        ZenuApiClient client = new ZenuApiClient();

        try {
            ApiResponse<List<EnquiryResp>> filteredResponse = client.getEnquiries(pageNumber, pageSize, filters);

            if (filteredResponse.getSuccess()) {
//                log.info("========>询盘请求成功!总记录数: {};总页数: {};当前页: {};每页大小: {}",
//                        filteredResponse.getPagination().getTotalRecords(),
//                        filteredResponse.getPagination().getTotalPages(),
//                        filteredResponse.getPagination().getPageNumber(),
//                        filteredResponse.getPagination().getPageSize());

                List<EnquiryResp> filteredData = filteredResponse.getData();

                // 获取所有的询盘ID
                List<Integer> ids = filteredData.stream().map(EnquiryResp::getId).collect(Collectors.toList());

                // 查询数据库是否已存在
                QueryWrapper<Enquiry> queryWrapper = new QueryWrapper<>();
                queryWrapper.lambda().in(Enquiry::getEnquiryId, ids);
                List<Enquiry> existEnquiries = dataEnquiriesServiceImpl.list(queryWrapper);

                if (!existEnquiries.isEmpty()) {
//                    log.info("========>数据库已存在{}条询盘数据,跳过", existEnquiries.size());
                    List<Integer> existIds = existEnquiries.stream().map(Enquiry::getEnquiryId).collect(Collectors.toList());
                    dataEnquiriesServiceImpl.remove(queryWrapper);
                    // 去除已存在的数据
//                    filteredData = filteredData.stream()
//                            .filter(enquiryResp -> !existIds.contains(enquiryResp.getId()))
//                            .collect(Collectors.toList());
                }

                List<Enquiry> enquiries = new ArrayList<>();

                for (EnquiryResp enquiryResp : filteredData) {
                    Enquiry enquiry = new Enquiry();
                    enquiry.setId(SnowflakeIdWorker.getSingleton().nextId());
                    enquiry.setComment(enquiryResp.getComment());
                    enquiry.setContactId(enquiryResp.getContactId());
                    enquiry.setOfficeId(enquiryResp.getOfficeId());
                    enquiry.setProjectId(enquiryResp.getProjectId());
                    enquiry.setEnquiryId(enquiryResp.getId());
                    enquiry.setType(enquiryResp.getType());

                    if (StringUtils.isNotEmpty(enquiryResp.getEnquiryDate())) {
                        enquiry.setEnquiryDate(DateUtils.parseISODate(enquiryResp.getEnquiryDate()));
                    }

                    if (enquiryResp.getCreatedDate() != null) {
                        enquiry.setCreatedDate(DateUtils.parseISODate(enquiryResp.getCreatedDate()));
                    }

                    enquiry.setAgentId(enquiryResp.getAgentId());
                    if (StringUtils.isNotEmpty(enquiryResp.getListingId())) {
                        enquiry.setListingId(Integer.parseInt(enquiryResp.getListingId()));
                    }
                    enquiry.setCreatedAt(new Date());
                    enquiry.setUpdatedAt(new Date());

                    enquiries.add(enquiry);
                }

                return enquiries;
            } else {
                StringBuilder errorMsg = new StringBuilder();
                errorMsg.append("========>请求失败!\n");
                if (filteredResponse.getMessages() != null) {
                    filteredResponse.getMessages().forEach(msg -> errorMsg.append("\n").append(msg));
                }
                log.error(errorMsg.toString());
                // 同步数据记录
                client.syncDataRecord(0, "Enquiry Data", "failed", "Enquiry", errorMsg.toString());
            }

        } catch (Exception e) {
            log.error("询盘API调用失败: {}", e.getMessage());
            // 同步数据记录
            client.syncDataRecord(0, "Enquiry Data", "failed", "Enquiry", e.getMessage());
        }

        return null;
    }

}
